package la.common.xml;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * Thread not safe
 * TODO optimalize
 * @author labile
 *
 */
public class XMLHelper {

	public static final XMLHelper instance = new XMLHelper();

	public XMLHelper() {
	}

	/**
	 * Return a NamespaceAware,ignoringElementContentWhitespace
	 * {@link DocumentBuilder}
	 * 
	 * @return
	 */
	public DocumentBuilder getDocBuilder() {
		DocumentBuilder docBuilder;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		dbf.setIgnoringElementContentWhitespace(true);
		try {
			docBuilder = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		}
		return docBuilder;
	}

	public XPath createXMLPath() {
		XPathFactory xpathFactory = XPathFactory.newInstance();
		return xpathFactory.newXPath();
	}
	
	public XPath createXMLPath(NamespaceContext nsContext) {
		XPath result = this.createXMLPath();
		result.setNamespaceContext( nsContext );
		return result;
	}

	/**
	 * Load xml doc from classloader, {@link RuntimeException} will throw if
	 * error.
	 * 
	 * @param resourcePath
	 * @return
	 */
	public Document sureLoadDocFromClassLoader(String resourcePath) {
		try {
			String uri = XMLHelper.class.getResource(resourcePath)
					.toString();
			Document doc2 = getDocBuilder().parse(uri);
			return doc2;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void removeMe(Node nodeToRemove) {
		Node parent = nodeToRemove.getParentNode();
		if( parent == null ) {
			throw new RuntimeException( "parent==null" );
		}
		parent.removeChild( nodeToRemove );
	}
}
